/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

angular.module('salesApp', ['ngAnimate', 'mgcrea.ngStrap', 'ui.router', 'sales.controllers', 'sales.services'])
    .constant('Settings', {
        Context: {
            path: path
        }
    })
    .run(['$rootScope', '$location', '$state', '$http', function ($rootScope, $location, $state, $http) {

        $rootScope.$ = layui.jquery;
        layui.use('element', function () {
            $rootScope.elements = layui.element();
            $rootScope.$ = layui.jquery;
            $rootScope.elements.on('tab(tab_demo)', function(data){
                // console.log(this); //当前Tab标题所在的原始DOM元素
                // console.log("index" + data.index); //得到当前Tab的所在下标
                // console.log(data.elem); //得到当前的Tab大容器
            });
            $rootScope.elements.on('nav(nav_left_menu)', function(elem){
                // console.log(elem); //得到当前点击的DOM对象
            });
            $rootScope.elements.on('nav(nav_right_menu)', function(elem){
                // console.log(elem); //得到当前点击的DOM对象
            });
        });
        $rootScope.arr = [];
        $rootScope.active = {
            tabAdd: function(id, titleName, content, url){
                if (tabIsExit(id) > -1) {//判断是否有tab页，>-1存在
                    var tabId = getTabId(titleName);
                    $rootScope.elements.tabChange('tab_demo', id);
                    $rootScope.$('#index_content').addClass('layui-show');
                    var obj=  $(".layui-tab").find("li.layui-this span");
                    $(obj).text(titleName);
                    obj.attr("data-url",url);
                    $state.go(url);
                    if(id==20 || id==24){
                        $rootScope.arr=[];
                    }
                } else {
                    addTab(id, titleName, content, url);
                }
            },
            //覆盖当前页面
            nextPage:function (id, titleName, content, url) {
                nextPage(id, titleName, content, url);
            },
            // 应收新建账单点击下一步
            nextBtn:function() {
                console.log($rootScope.arr)
                // var recidList = $("input[name='id_name']:checked");
                // var recidVal = recidList.val();
                if($rootScope.arr.length <= 0){
                    layer.msg('请选中新建项');
                }else{
                    $http.post("receivable/insert-temp",{
                        "orderIds":$rootScope.arr
                    }).success(function(res){
                        if(res.success) {
                            var dataparmet={data: res.data};
                            nextPagearmet("", "应收生成账单", dataparmet, 'generateBillR')
                        }else{
                            layer.msg('选择订单信息错误！');
                        }
                    });
                }
            },
            // 生成账单
            createBtn:function() {
                $http.post("receivable/create-rece",{
                    "versionNo":$("#versionNo").val(),
                    "invoiceStatus":$("#invoiceStatus").val()
                }).success(function(res){
                    if(res.success) {
                        nextPagearmet('', '应收账单管理','', 'receivable');
                    }else{
                        layer.msg('生成账单失败！');
                    }
                });
            },

            // 确认账单页面
            confirmBtn:function(id,titleName,text,url) {
                var recidList = $("input[name='id_name']:checked");
                var recidVal = recidList.val();
                if (!recidVal) {
                    layer.msg('请选择未对账账单！');
                } else {
                    if (recidList.length > 1) {
                        layer.msg('请选中一条账单！');
                    }else {

                        var rVal = recidVal.split('-');
                        if(rVal[1] !=10){
                            layer.msg('请选择未对账账单！');
                        }else {
                            $rootScope.elements.tabChange('tab_demo', id);
                            var obj = $(".layui-tab").find("li.layui-this span");
                            $(obj).text(titleName);
                            $state.go('confirmBillR', {'data': rVal[0]});
                        }
                    }
                }
            },

            // 确认账单按钮
            confirm : function () {
                layer.confirm('是否确认账单？', {
                    title: '提示'
                    , btn: ['确认', '取消'] //按钮
                }, function () {
                    $http.post("receivable/confirm-rece", {
                        "id": $("#id").val(),
                        "invoiceStatus":$("#invoiceStatus").val()
                    }).success(function (res) {
                        if (res.success) {
                            layer.msg('已成功确认', {
                                icon: 1
                            });
                            $state.go('receivable');
                        } else {
                            layer.msg('确认失败', {
                                icon: 1
                            });
                        }
                    });
                })
            },

            // 收款管理，付款确认跳转页面
            confirmProceed:function(id,titleName,text,url) {
                var recidList = $("input[name='id_name']:checked");
                var recidVal = recidList.val();
                if (!recidVal) {
                    layer.msg('请选择未收款账单！');
                } else {
                    if (recidList.length > 1) {
                        layer.msg('请选中一条账单！');
                    }else {
                        var rVal = recidVal.split('-');
                        if(rVal[1] !=10){
                            layer.msg('请选择未收款账单！');
                        }else {
                            nextPagearmet('', '收款确认', {data: rVal[0]}, 'proceed');
                        }
                    }
                }
            },

            // 确认收款按钮
            confirmProBtn : function () {
                if($("#proceedDate").val()==null||$("#proceedDate").val()==''){
                    layer.msg('请选择收款确认日期！');
                }else{
                    layer.confirm('是否确认收款？', {
                        title: '提示'
                        , btn: ['确认', '取消'] //按钮
                    }, function () {
                        $http.post("receivable/confirm-proceed", {
                            "id": $("#id").val(),
                            "billDateStartString":$("#invoiceDate").val(),
                            "billDateEndString":$("#proceedDate").val()
                        }).success(function (res) {
                            if (res.success) {
                                layer.msg('已成功确认', {
                                    icon: 1
                                });
                                $state.go('proceedManage');
                            } else {
                                layer.msg('确认失败', {
                                    icon: 1
                                });
                            }
                        });
                    })
                }
            },

            // 确认账单按钮
            confirmBill : function () {
                layer.confirm('是否确认账单？', {
                    title: '提示'
                    , btn: ['确认', '取消'] //按钮
                }, function () {
                    $http.post("payable/create-payable-bill", {
                        "billId": $("#billId").val(),
                        "invoiceStatus":$("#invoiceStatus").val()
                    }).success(function (res) {
                        if (res.success) {
                            layer.msg('已成功确认', {
                                icon: 1
                            });
                            $state.go('payable');
                        } else {
                            layer.msg('确认失败', {
                                icon: 1
                            });
                        }
                    });
                })
            },
            btnNext:function() {
                console.log($rootScope.arr)
                if($rootScope.arr <= 0){
                    layer.msg('请选中新建项');
                }else{
                    $http.post("payable/insert-temp",{
                        "ids":$rootScope.arr
                    }).success(function(res){
                        $state.go('generateBill',{data:res.data});
                    });
                }
            },
            select:function(n){
                var recidList = $("input[name='id_name']:checked");
                if(n.x.state==true){
                    n.x.state=false;
                    var ss= n.x.customerOrderCode;
                    $rootScope.arr.pop(ss)
                }else{
                    n.x.state=true;
                    var ss= n.x.customerOrderCode;
                    $rootScope.arr.push(ss);
                }
                alert($rootScope.arr);
            },
            generateBill:function() {
                $http.post("payable/generate-bill",{
                    "invoiceStatus":$("#invoiceStatus").val(),
                    "versionNo":$("#versionNo").val()
                }).success(function(res){
                    if(res.success) {
                        nextPagearmet('', '应付账单管理 ', '', 'payable');
                    }else{
                        layer.msg('生成账单失败！');
                    }
                });
            },
            confirmPayable:function() {
                var payidList = $("input[name='id_name']:checked");
                var payidVal = payidList.val();
                if (!payidVal) {
                    layer.msg('请选择未对账账单！');
                } else {
                    if (payidList.length > 1) {
                        layer.msg('请选中一条账单！');
                    }else {
                        var pVal = payidList.val().split('-');
                        if(pVal[1] !=10){
                            layer.msg('请选择未对账账单！');
                        }else {
                            $state.go('confirmBill', {data: pVal[0]});
                        }
                    }
                }
            },
            //付款管理：付款确认跳转页面
            paymentBtn: function() {
                var payidList = $("input[name='id_name']:checked");
                var payidVal = payidList.val();
                if (!payidVal) {
                    layer.msg('请选择未付款账单！');
                } else {
                    if (payidList.length > 1) {
                        layer.msg('请选中一条账单！');
                    }else {
                        var pVal = payidVal.split('-');
                        if(pVal[1] == 30){
                            layer.msg('请选择未付款账单！');
                        }else {
                           nextPagearmet('', '付款确认', {data: pVal[0]}, 'payment');
                        }
                    }
                }
            },
            confirmPayBtn: function () {
                if ($("#payDate").val() == null || $("#payDate").val() == "") {
                    layer.msg('请输入付款确认日期');
                }else{
                layer.confirm('是否确认付款？', {
                    title: '提示'
                    , btn: ['确认', '取消'] //按钮
                }, function () {
                    $http.post("payable/confirm-payment", {
                        "id": $("#id").val(),
                        "invoiceDate": $("#invoiceDate").val(),
                        "payDate": $("#payDate").val()
                    }).success(function (res) {
                        if (res.success) {
                            layer.msg('已成功确认', {
                                icon: 1
                            });
                            $state.go('paymentManage');
                        } else {
                            layer.msg('确认失败', {
                                icon: 1
                            });
                        }
                    });
                })
             }
            }
        };





        //刷新事件(刷新，默认显示首页)
        $rootScope.$on('$locationChangeStart', function (event) {
            var  go_href =$(".layui-tab").find("li.layui-this span").attr("data-url");
            if(!go_href){
                $state.go('home');
            }else{
                event.preventDefault();
            }
        });
        //点击新增
        function nextPage(id, titleName, content, url){
           // $rootScope.elements.tabChange('tab_demo', id);
            //获取当前的的table对象
            var obj=  $(".layui-tab").find("li.layui-this span");
            //新增之后更改 table标题
            $(obj).text(titleName);
            //新增之后更改table的data-url
            $(obj).attr("data-url",url);
            //跳转页面
            $state.go(url);
            //这里面只改了 一个
        }
        //点击新增
        function nextPagearmet(id, titleName, parmet, url){
            // $rootScope.elements.tabChange('tab_demo', id);
            //获取当前的的table对象
            var obj=  $(".layui-tab").find("li.layui-this span");
            //新增之后更改 table标题
            $(obj).text(titleName);
            //新增之后更改table的data-url
            $(obj).attr("data-url",url);
            //跳转页面
            $state.go(url,parmet);
        }



        function addTab(id, titleName, content, url) {//添加tab页
            var title = '';
            title += '<span id = "' + id + '" data-url ="'+ url +'">' + titleName + '</span>';
            title += '<i class="layui-icon layui-unselect layui-tab-close" data-id ="'+ id +'">&#x1006;</i>';
            var div = 'div_' + id;
            //添加tab
            $rootScope.elements.tabAdd('tab_demo', {
                title: title,
                id: id
            });

            $rootScope.$('.layui-tab-content').children('div.layui-tab-item').eq(1).remove();
            $rootScope.$('#index_content').addClass('layui-show');

            $rootScope.elements.tabChange('tab_demo', id);

            $rootScope.$('.layui-tab').find('li').children('i.layui-tab-close[data-id='+ id +']').on('click', function () {
                $rootScope.elements.tabDelete("tab_demo", $(this).parent('li').attr('lay-id')).init();//关闭tab_title
                //点击x，关闭tab页
                var  go_href =$(".layui-tab").find("li.layui-this span").attr("data-url");
                if(!go_href){
                    $state.go('home');
                }else{
                    $state.go(go_href);
                }
            });
            //点击tab，进行切换
                $rootScope.$('.layui-tab').find('li[lay-id='+id+']').bind('click', function () {
                    var tab_url = $(this).find('span').attr('data-url');
                    $state.go(tab_url);//切换tab页
            });
            $state.go(url);//切换首页
        }

        function getTabId(title) {//获取tab页的id
            var tabId = -1;
            $rootScope.$('.layui-tab').find('li').each(function (i, e) {
                var $cite = $(this).children('span');
                if ($cite.text() === title) {
                    tabId = $(this).attr('lay-id');
                }
            });
            return tabId;
        }

        function tabIsExit(id) {//获取tab页是否存在，存在1，不存在-1
            var tabIndex = -1;
            $rootScope.$('.layui-tab').find('li').each(function (i, e) {
                var $cite = $(this).children('span');
                if ($cite.attr("id") === id) {
                    tabIndex = i;
                }
            });
            return tabIndex;
        }

        // 显示大图
        $rootScope.showBigImg = function (imageURL) {
            $rootScope.image.picKey = imageURL;
            $rootScope.image.flg = true;
        };

        // 隐藏大图
        $rootScope.hideImage = function () {
            $rootScope.image.picKey = '';
            $rootScope.image.flg = false;ßßßßßßß
        };

    }])
    .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider) {
        $urlRouterProvider.otherwise('home');//默认跳转首页

        var path = getRootPath();
        $stateProvider
            .state('home', {
                url: '/home',
                templateUrl: 'index/home',
                controller: 'SalesIndexCtrl'
            })
            .state('demo1', {
                url: '/demo1',
                templateUrl: path+'/index/demo1',
                controller: 'Demo1Ctrl'
            })
            .state('demo2', {
                url: '^/temp/demo2',
                templateUrl: 'temp/demo2.jsp',
                controller: 'Demo2Ctrl'
            })
            .state('demo3', {
                url: '^/temp/demo3',
                templateUrl: 'temp/demo3.jsp',
                controller: 'Demo3Ctrl'
            })
            .state('demo4', {
                url: '^/temp/demo4',
                templateUrl: 'temp/demo4.jsp',
                controller: 'Demo4Ctrl'
            })
            .state('demo5', {
                url: '^/temp/demo5',
                templateUrl: 'temp/demo5.jsp',
                controller: 'Demo5Ctrl'
            })
            .state('demo6', {
                url: '^/temp/demo6',
                templateUrl: 'temp/demo6.jsp',
                controller: 'Demo6Ctrl'
            })
            .state('demo7', {
                url: '^/temp/demo7',
                templateUrl: 'temp/demo7.jsp',
                controller: 'Demo7Ctrl'
            })
            .state('demo8', {
                url: '^/temp/demo8',
                templateUrl: 'temp/demo8.jsp',
                controller: 'Demo8Ctrl'
            })
            .state('receivable', {
                url: '/receivable',
                templateUrl:  path+'/index/receivable',
                controller: 'receivableCtrl'
            })
            .state('newBillR', {
                url: '/newBillR',
                templateUrl:  path+'/index/newBillR',
                controller: 'newBillRCtrl'
            })
            .state('generateBillR', {
                url: '/generateBillR',
                params:{'data':null},
                templateUrl:  path+'/index/generateBillR',
                controller: 'generateBillRCtrl'
            })
            .state('confirmBillR', {
                url: '/confirmBillR',
                params:{'data':null},
                templateUrl:  path+'/index/confirmBillR',
                controller: 'confirmBillRCtrl'
            })
            .state('payable', {
                url: '/payable',
                templateUrl:  path+'/index/payable',
                controller: 'payableCtrl'
            })
            .state('newBill', {
                url: '/newBill',
                templateUrl:  path+'/index/newBill',
                controller: 'newBillCtrl'
            })
            .state('generateBill', {
                url: '/generateBill',
                params:{'data':null},
                templateUrl:  path+'/index/generateBill',
                controller: 'generateBillCtrl'
            })
            .state('confirmBill', {
                url: '/confirmBill',
                params:{'data':null},
                templateUrl:  path+'/index/confirmBill',
                controller: 'confirmBillCtrl'
            })
            .state('proceedManage', {
                url: '/proceedManage',
                params:{'data':null},
                templateUrl:  path+'/index/proceedManage',
                controller: 'proceedManageCtrl'
            })
            .state('proceed', {
                url: '/proceed',
                params:{'data':null},
                templateUrl:  path+'/index/proceed',
                controller: 'proceedCtrl'
            })
            .state('paymentManage', {
                url: '/paymentManage',
                params:{'data':null},
                templateUrl:  path+'/index/paymentManage',
                controller: 'paymentManageCtrl'
            })
            .state('payment', {
                url: '/payment',
                params:{'data':null},
                templateUrl:  path+'/index/payment',
                controller: 'paymentCtrl'
            })
            .state('orderPrice', {
                url: '/orderPrice',
                templateUrl:  path+'/index/orderPrice',
                controller: 'orderPriceCtrl'
            })
            .state('wayBillPrice', {
                url: '/wayBillPrice',
                templateUrl:  path+'/index/wayBillPrice',
                controller: 'wayBillPriceCtrl'
            })
            .state('receiptAudit', {
                url: '/receiptAudit',
                templateUrl:  path+'/index/receiptAudit',
                controller: 'receiptAuditCtrl'
            });



        // 使angular $http post提交和jQuery一致
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

        // Override $http service's default transformRequest
        $httpProvider.defaults.transformRequest = [function (data) {
            /**
             * The workhorse; converts an object to x-www-form-urlencoded serialization.
             * @param {Object} obj
             * @return {String}
             */
            var param = function (obj) {
                var query = '';
                var name, value, fullSubName, subName, subValue, innerObj, i;

                for (name in obj) {
                    value = obj[name];

                    if (value instanceof Array) {
                        for (i = 0; i < value.length; ++i) {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value instanceof Object) {
                        for (subName in value) {
                            subValue = value[subName];
                            fullSubName = name + '[' + subName + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    } else if (value !== undefined && value !== null) {
                        query += encodeURIComponent(name) + '='
                            + encodeURIComponent(value) + '&';
                    }
                }

                return query.length ? query.substr(0, query.length - 1) : query;
            };

            return angular.isObject(data) && String(data) !== '[object File]'
                ? param(data)
                : data;
        }];
    }]);